package com.xiehua.task.client.handler;

import com.xiehua.task.client.job.JobExecuter;
import com.xiehua.task.intf.AbsBusinessHandler;
import com.xiehua.task.msg.TaskRegRespBody;
import com.xiehua.task.prop.XiehuaConfig;
import com.xiehua.task.protocol.TaskPacket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.ChannelContext;
import org.tio.utils.json.Json;

import java.util.concurrent.atomic.AtomicLong;

import static com.xiehua.task.prop.XiehuaConfig.KEY_CLIENT_DELAY_TASK_EXECUTER;

/**
 * @author Mr.zhang
 * 2018年3月27日 下午9:51:28
 */
public class TaskRegRespHandler extends AbsBusinessHandler<TaskRegRespBody> {

	private static Logger log = LoggerFactory.getLogger(TaskRegRespHandler.class);


	AtomicLong tokenSeq = new AtomicLong();

	/**
	 *
	 * @author tanyaowu
	 */
	public TaskRegRespHandler() {
	}

	/**
	 * @return
	 * @author tanyaowu
	 */
	@Override
	public Class<TaskRegRespBody> bodyClass() {
		return TaskRegRespBody.class;
	}

	/**
	 * @param packet
	 * @param bsBody
	 * @param channelContext
	 * @return
	 * @throws Exception
	 * @author tanyaowu
	 */
	@Override
	public Object handler(TaskPacket packet, TaskRegRespBody bsBody, ChannelContext channelContext) throws Exception {
		log.info("收到Task注册响应消息:{}", Json.toJson(bsBody));
		TaskPushReqHandler.pool.submit(()->{
			try {
				Class jobExecuterClass = Class.forName(XiehuaConfig.getInstance().get(KEY_CLIENT_DELAY_TASK_EXECUTER));
				JobExecuter executer = (JobExecuter) jobExecuterClass.newInstance();
				executer.asynNotifyResult(bsBody.getRegTaskReqId(),bsBody.getTaskId(),bsBody.isSuccess());
			}catch (ClassNotFoundException |InstantiationException | IllegalAccessException e){
				log.error("客户端配置的executer不能实例化",e);
			}
		});
		return null;
	}

	private String newToken() {
		return System.currentTimeMillis() + "_" + tokenSeq.incrementAndGet();
	}
}
